package com.gh.shop.product.exception;

import com.gh.common.exception.CodeEnum;
import com.gh.common.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * date: 2020/7/14 17:44
 * 全局处理异常
 *
 * @author GH
 * QQ 1124813753
 */
@RestControllerAdvice(basePackages = "com.gh.shop.product.controller")
public class GlobalControlException {
    /**
     * 处理数据校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();

        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(fieldError -> {
            map.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        return R.error(CodeEnum.VALID_EXCEPTION.getCode(), CodeEnum.VALID_EXCEPTION.getMsg())
                .put("data", map);
    }

    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable) {
        return R.error(CodeEnum.UNKNOWN_EXCEPTION.getCode(), CodeEnum.UNKNOWN_EXCEPTION.getMsg());
    }
}
